#!/bin/env python

"""
Test plotter for use with Dingo. Expects a string of the form

Sensor<int>\t<int>\t<float>

to be plotted.
"""

__author__ = 'Sarah Mount <s.mount@wlv.ac.uk>'
__date__ = 'March 2007'

import math, plotter, re

DEBUG = False

### Mote calibration config
config = 'motes.cfg'

### Unmarshalling the accel data
rexp = re.compile('^(Sensor?-\d)\s+(\d+)\s+(\d+\.\d+)$')# str ws int ws float EOS
sample_rate = 8.0                       # Sample rate in Hz
offset_d = {}				# Mote calibration default
offset = (0.0, 0.0)			# Currently used calibration offset


class AccelUnmarshaller(plotter.Unmarshaller):
    	def __init__(self,
		     offset_d,
		     offset,
		     isLine=False):
                self.isLine = True			# Plot lines (or points)
            	self.title = 'Average network temperature'	# Plot title
		self.max_data = 5   # Max datapoints
                self.xlabel = 'Time(secs)'	# X-axis label
                self.ylabel = 'Temp (C)'	# Y-axis label
                self.offset_d = offset_d	# Data offsets
                self.offset = offset		# Current offset
		self.config = {'Sensor-1':plotter.SeriesConfig(legend='Sensor -1'),
			       'Sensor0':plotter.SeriesConfig(legend='Sensor 0',
						    	    colour='red'),
			       'Sensor1':plotter.SeriesConfig(legend='Sensor 1',
						    	    colour='green'),
			       'Sensor2':plotter.SeriesConfig(legend='Sensor 2',
						    	    colour='yellow'),
			       'Sensor3':plotter.SeriesConfig(legend='Sensor 3',
						    	    colour='grey'),
       			       'Sensor4':plotter.SeriesConfig(legend='Sensor 4',
						    	    colour='blue')}
		return
	def unmarshall(self, s):
	   	"""Unmarshall string data coming from the socket which will be
	    	mote-name, time, av. temp.
	    	"""
	    	if DEBUG: print 'string from mote socket:', s
	    	m = rexp.search(s)
	    	if not m:
	    	    return None
		mote = m.group(1)
	    	x = int(m.group(2))
	    	y = float(m.group(3))
	    	if DEBUG:
			print mote
	    	    	print '(x,y) =', (x,y)
	    	return (mote, x, y)


if __name__ == '__main__':
    import ConfigParser, sys
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option('-f', '--file', dest='config', default=config,
                      help='Configuration file')
    (options, args) = parser.parse_args()
    if options.config:
        config = options.config

    # Configuration of mote calibration data
    cp = ConfigParser.ConfigParser()
    fp = open(config)
    cp.readfp(fp)
    fp.close()
    ri = re.compile('^\((\d+),\s*(\d+)\)$')
    rf = re.compile('^\((\d+\.\d+),\s*(\d+\.\d+)\)$')
    try:
    	for i in cp.items('Mote Calibration'):
            m = ri.search(i[1]) or rf.search(i[1])
            if m:
                offset_d[i[0]] = (float(m.group(1)), float(m.group(2)))
    except:
        offset_d = {'mote0':(0.0, 0.0)}
    else:
        offset = offset_d['mote0']

    # Print some info to STDOUT
    print 'Sample rate', sample_rate, 'Hz'
    print 'Current calibration offset', offset
    
    # Run GUI
    plotter.PlottingApp.unmarshaller = AccelUnmarshaller(offset_d, offset)
    plotter.PlottingApp(0).MainLoop()
    sys.exit(0)
